import { onMounted, reactive, shallowRef } from "vue";
import { getDemoList } from "@/api/datalist";
import type Node from "element-plus/es/components/tree/src/model/node";
import { isArray } from "@pureadmin/utils";

interface Tree {
  name: string;
  code?: string;
  children?: Tree[];
}

export const useNav = getChartList => {
  const state = reactive({
    width: 300,
    active: "first"
  });

  const treeData = shallowRef<Tree[]>([]);

  const defaultProps = {
    children: "children",
    label: "name",
    isLeaf: data => {
      if (isArray(data) || data.children) {
        return false;
      }
      return true;
    }
  };
  const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
    getDemoList<Tree[]>({ name: node.label }).then(res => {
      resolve(res.data);
    });
  };
  const handleNodeClick = (data: Tree) => {
    if (data.code) {
      getChartList(data.code);
    }
  };

  onMounted(() => {
    getDemoList<Tree[]>().then(res => {
      treeData.value = res.data;
    });
  });

  return {
    state,
    treeData,
    defaultProps,
    loadNode,
    handleNodeClick
  };
};
